package com.eascs.workflow.massSms.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.doc.excel.RowReadHandler;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.Render;
import com.eascs.site.view.ViewContext;
import com.eascs.workflow.common.entity.sys.WfMessage;
import com.eascs.workflow.massSms.service.IMassSmsService;
import com.eascs.workflow.massSms.vo.MassSmsVo;

@RestController
@RequestMapping("/massSmsRest")
public class MassSmsRestController extends BaseRestController {
	@Inject
	IMassSmsService iMassSmsService;

	@RequestMapping(value = "/detail")
	public BaseRestResult<String> detail(String requestId) {
		WfMessage wf = iMassSmsService.findByrequestId(requestId);
		ViewContext.put("wf", wf);
		return HtmlRestResult.popHtmlFragment("massSms/sms_detail");
	}

	@RequestMapping(value = "/add_sms")
	public BaseRestResult<String> addSms() {
		return HtmlRestResult.popHtmlFragment("massSms/add_sms");
	}

	@RequestMapping(value = "/save_sms")
	public BaseRestResult<String> saveSms(MassSmsVo vo) {
		if(vo==null && StringUtil.isBlank(vo.getContactors())){
			return BaseRestResult.error("请上传短信联系人！");
		}else{
			Map<String, String> map = iMassSmsService.saveSms(vo);
			String error = map.get("error");
			if(StringUtil.isNotBlank(error)){
				return BaseRestResult.error(error+"上传失败，请重新上传！");
			}else{
				return BaseRestResult.info("添加成功").refresh();
			}
		}
		
	}

	@RequestMapping("/download")
	public BaseRestResult<String> download(HttpServletResponse httpServletResponse, HttpServletRequest request) {
		BaseRestResult<String> result = null;
		String file = MassSmsRestController.class.getResource("/excelTemplate/massSms.xls").getPath();

		OutputStream os = null;
		try {
			String outfile = "massSms.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(file);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
		return result;
	}

	@RequestMapping("/uploadExecl")
	public BaseRestResult<Render[]> uploadExcel(@RequestParam(value = "file", required = false) MultipartFile file) {
		// 文件格式校验
		if (!file.getOriginalFilename().endsWith(".xls")) {
			try {
				throw new RuntimeException("模版错误,请使用提供的联系人上传模板导入数据!");
			} catch (Exception e) {
				String message = e.getMessage();
				//message = e.getMessage().substring(27, message.length());
				return BaseRestResult.render(new Render[] { new Render("#errorMessage1", message)});
			}
		}
		// 上传内容校验
		ArrayList<String> list = new ArrayList<String>();
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			ExcelApiHelper.readHandle(inputStream, new RowReadHandler() {
				@Override
				public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
					check(sheetIndex, rowIndex, rowDatas);
					if (rowIndex > 0) {
						 DecimalFormat df = new DecimalFormat("#");
						list.add( df.format(rowDatas[0] == null ? "" : rowDatas[0]));
					}
				}
			});
		} catch (RuntimeException e) {
			String message = e.getMessage();
			message = e.getMessage().substring(27, message.length());
			return BaseRestResult.render(new Render[] { new Render("#errorMessage1", message)});
		}
		

		StringBuffer s = new StringBuffer();
		if (list != null && list.size() > 0) {
			if (list.size() == 1) {
				s.append(list.get(0));
			}else{
				for (int i = 0; i < list.size(); i++) {
					if (list.size() == i + 1) {
						s.append(list.get(i));
					} else {
						s.append(list.get(i)).append(";");
					}
				}
			}
		}
		return BaseRestResult.render(new Render[] { new Render("#errorMessage1", "导入成功"), new Render("#smsContent", s.toString()),
						new Render("#smsSize", "联系人总数：" + String.valueOf(list.size())) });
	}

	@SuppressWarnings("unused")
	private void check(int sheetIndex, int rowIndex, Object[] rowDatas) throws RuntimeException {

		String phone = "";
		if (sheetIndex == 0 && rowIndex > 1) {
			String message = "第" + rowIndex + "行：";
			 DecimalFormat df = new DecimalFormat("#");
			for (int i = 0; i < rowDatas.length; i++) {
				if (i == 0) {
					try {
						phone = df.format(rowDatas[0] == null ? "" : rowDatas[0]);
					} catch (Exception e) {
						throw new RuntimeException(message + "手机号码格式错误,请修改后再导入"); 
					}
				}
			}
			/*
			 * if (phone == null || "".equals(phone)) { throw new
			 * RuntimeException(message + "手机号码不能为空,请修改后再导入"); }
			 */
			
			if (!isChinaPhoneLegal(phone)) { 
				throw new RuntimeException(message + "手机号码格式错误,请修改后再导入"); 
			}
			 
			if (Integer.valueOf(rowIndex) > 500) {
				throw new RuntimeException("一次最多只能导入500个联系人,请修改后再导入");
			}

		}

	}

	public static boolean isChinaPhoneLegal(String str) {
		String regExp = "^\\d{11}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	
	public static void main(String[] args) {
		System.out.println(isChinaPhoneLegal("18177287676"));
	}

}
